import { Message } from 'element-ui';
import { uniq } from '@/utils';
const medium = {
  state: {
    shopCarList: jsonParse(localStorage.getItem('shopCarList')),
    filterOpen: false,
    userAuthType: 1 // 1: 销售 2:媒介 3:管理员
  },
  mutations: {
    SET_SHOPCAR: (state, data) => {
      state.shopCarList = data;
      localStorage.setItem('shopCarList', JSON.stringify(data));
    },
    SET_USER_TYPE: (state, data) => {
      state.userAuthType = data;
    },
    SET_FILTER_OPEN: (state, data) => {
      state.filterOpen = data;
    }
  },
  actions: {
    setShopCar({ commit }, data) {
      const platform = String(data.platform);
      const shopCarList = jsonParse(localStorage.getItem('shopCarList'));
      if (shopCarList.length > 0) {
        let flag = false;
        shopCarList.forEach(i => {
          if (String(i.platform) === platform) {
            i.items = uniq(i.items.concat(data.items), 'mediumId');
            flag = true;
          }
        });
        if (!flag) {
          shopCarList.push({
            platform: platform,
            items: data.items
          });
        }
      } else {
        shopCarList.push({
          platform: platform,
          items: data.items
        });
      }
      commit('SET_SHOPCAR', shopCarList);
      Message({
        type: 'success',
        message: '添加成功'
      });
    },
    clearShopCar({ commit }) {
      localStorage.setItem('shopCarList', '[]');
      commit('SET_SHOPCAR', []);
    },
    deleteShopCar({ commit }, { mediumId, platform }) {
      const shopCarList = jsonParse(localStorage.getItem('shopCarList'));
      shopCarList.forEach((i, index) => {
        if (i.platform === platform) {
          for (let j = 0; j < i.items.length; j++) {
            if (i.items[j].mediumId === mediumId) {
              i.items.splice(j, 1);
              break;
            }
          }
          if (i.items.length <= 0) {
            shopCarList.splice(index, 1);
          }
        }
      });
      commit('SET_SHOPCAR', shopCarList);
    }
  }
};

function jsonParse(str) {
  if (str && str !== '') {
    try {
      return JSON.parse(str);
    } catch (error) {
      return [];
    }
  }
  return [];
}

export default medium;
